let connect = require('../database/connect');
/**
 * @param tableName
 * @param params type is object  use it to handle values
 * @param where type is object , this is a condition
 */
const update = async (tableName, params, where) => { 
  return await dealQuery(`update ${tableName} set ${convertParams(params)} where ${convertWhere(where)}`);
};

const insert = async (tableName, params) => {
  // {name:'xiaosan',age:10,pwd....}
  // 'name,age,pwd'    '"xiaosan",10'
  let keys = Object.keys(params);
  let values = keys.map(item => {
    if (typeof params[item] === 'string') {
      return `'${params[item]}'`;
    }
    return params[item];
  }).join(',');

  keys = keys.join(',');
  // insert into 表名 (键keys) values (值values)
  return await dealQuery(`insert into ${tableName} (${keys}) values (${values})`);
};

const deletes = async (tableName, where) => {
  return await dealQuery(`delete from ${tableName} where ${convertWhere(where)}`);
};

/**
 *
 * @param tableName
 * @param keys ['id','name']
 * @param where
 * @returns {Promise<*>}
 */
const select = async (tableName, where, keys = []) => {
  let newKeys = '';
  if (keys.length !== 0) {
    newKeys = keys.join(',');
  } else {
    newKeys = '*';
  }
  // keys 如果没传过来 变成 *
  let sql = '';
  if (where) {
    sql = `select ${newKeys} from ${tableName} where ${convertWhere(where)}`;
  } else {
    sql = `select ${newKeys} from ${tableName}`;
  }
  return await dealQuery(sql);
};

function convertParams(params) {
  return Object.keys(params).map(item => {
    if (params[item]) {
      if (typeof params[item] === 'string') {
        return `${item}='${params[item]}'`;
      }
      return `${item}=${params[item]}`;
    }
  }).filter(item => item).join(',');
}

function convertWhere(where) {
  return Object.keys(where).map(item => {
    if (where[item]) {
      if (typeof where[item] === 'string') {
        return `${item}='${where[item]}'`;
      }
      return `${item}=${where[item]}`;
    }
  }).filter(item => item).join(' and ');
}

async function dealQuery(sql) {
  let result;
  try {
    result = await new Promise((resolve, reject) => {
      connect.query(sql, (err, res) => err ? reject(err) : resolve(res));
    });
  } catch (err) {
    result = err;
  }
  return result;
}

module.exports = {
  update, insert, deletes, execute: dealQuery, select
};
